# -*- coding:utf-8 -*-

from flask import Flask
import redis
from flask.ext.basicauth import BasicAuth
from flask_wtf.csrf import CSRFProtect
from flask_session import Session
from config import config
import logging
from logging.handlers import RotatingFileHandler
from flask import make_response,render_template
from flask_wtf.csrf import generate_csrf


logging.basicConfig(level=logging.DEBUG)
file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024*1024*100, backupCount=10)
formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
file_log_handler.setFormatter(formatter)
logging.getLogger().addHandler(file_log_handler)
redis_store = None
csrf = CSRFProtect()
basic_auth = BasicAuth()
def create_app(config_name):

    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://root:mysql@127.0.0.1:3306/zczh_web"
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['SQLALCHEMY_ECHO'] = False

    app.config['BASIC_AUTH_USERNAME'] = '123'
    app.config['BASIC_AUTH_PASSWORD'] = '123'

    app.config['WHOOSH_BASE'] = 'path/to/whoosh/base'

    from flask import url_for
    from werkzeug.utils import redirect
    from project_zczh import basic_auth
    @app.route('/admin')
    @basic_auth.required
    def secret_view():
        return redirect(url_for('admin.index'))

    @app.route('/')
    def get_index():
        token = generate_csrf()
        response = make_response(render_template('login.html', token=token))
        response.set_cookie('csrf_token', token)
        return response
    Session(app)
    # csrf.init_app(app)
    global basic_auth
    basic_auth.init_app(app)
    global redis_store
    redis_store=redis.StrictRedis(host=config[config_name].REDIS_HOST,port=config[config_name].REDIS_PORT)
    from tool.common import RegexConverter
    app.url_map.converters['re'] = RegexConverter
    import project_1
    app.register_blueprint(project_1.project,url_prefix='/v1.0')
    return app

